﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Custom.Controls
{
    public class ProcessManager
    {
        private static ProcessManager manager = null;
        private ProcessForm processForm = null;
        public delegate void DoWork();

        public static ProcessManager Instance
        {
            get
            {
                if (manager == null)
                {
                    manager = new ProcessManager();
                }

                return manager;
            }
        }

        public void Show(Form owner, int max, DoWork work)
        {
            processForm = new ProcessForm()
            {
                Max = max
            };
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(10);
                work.Invoke();
            });
            processForm.ShowDialog(owner);
        }

        public void ReportProgress(int value, string text = "")
        {
            if (processForm != null)
            {
                processForm.SetValueText(value, text);
            }
        }

        public void Close()
        {
            if (processForm != null && processForm.IsHandleCreated)
            {
                processForm.Close();
                processForm = null;
            }
        }

        public void CloseAysnc(Form owner)
        {
            if (owner != null)
            {
                owner.Invoke(new Action(() =>
                {
                    if (processForm == null) return;
                    processForm.Opacity = 0;
                    processForm.Close();
                    processForm = null;
                }));
            }
        }
    }
}
